﻿using KAs.Application.Contract.Dto;
using KAs.Cache;

namespace Microsoft.Extensions;

/// <summary>
/// token缓存相关扩展封装
/// </summary>
public static class TokenCacheExtensions
{
    private static string SetTokenKey(string token)
    {
        return token;
    }

    /// <summary>
    /// 设置token
    /// </summary>
    /// <param name="cache"></param>
    /// <param name="userInfoDto"></param>
    /// <param name="seconds"></param>
    /// <returns></returns>
    public static string SetToken(this ICache cache, UserInfoDto userInfoDto, double seconds = 3600)
    {
        var token = Guid.NewGuid().ToString("N");
        cache.Set(SetTokenKey(token), userInfoDto, TimeSpan.FromSeconds(seconds));
        return token;
    }
    /// <summary>
    /// 设置token
    /// </summary>
    /// <param name="cache"></param>
    /// <param name="userInfoDto"></param>
    /// <param name="seconds"></param>
    /// <returns></returns>
    public static async Task<string> SetTokenAsync(this ICache cache, UserInfoDto userInfoDto, double seconds = 3600)
    {
        var token = Guid.NewGuid().ToString("N");
        await cache.SetAsync(SetTokenKey(token), userInfoDto, TimeSpan.FromSeconds(seconds));
        return token;
    }

    /// <summary>
    /// 根据token获取用户信息
    /// </summary>
    /// <param name="cache"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    public static UserInfoDto GetToken(this ICache cache, string token)
    {
        return cache.Get<UserInfoDto>(SetTokenKey(token));
    }
    /// <summary>
    /// 根据token获取用户信息
    /// </summary>
    /// <param name="cache"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    public static async Task<UserInfoDto> GetTokenAsync(this ICache cache, string token)
    {
        return await cache.GetAsync<UserInfoDto>(SetTokenKey(token));
    }
    /// <summary>
    /// 刷新缓存时间
    /// </summary>
    /// <param name="cache"></param>
    /// <param name="token"></param>
    public static void RefreshToken(this ICache cache, string token, double seconds = 3600)
    {
        cache.Refresh(SetTokenKey(token), TimeSpan.FromSeconds(seconds));
    }

    /// <summary>
    /// 刷新缓存时间
    /// </summary>
    /// <param name="cache"></param>
    /// <param name="token"></param>
    /// <returns></returns>
    public static async Task RefreshTokenAsync(this ICache cache, string token, double seconds = 3600)
    {
        await cache.RefreshAsync(SetTokenKey(token), TimeSpan.FromSeconds(seconds));
    }
}
